import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/widget/icon_text.dart';
import 'package:flutter/material.dart';

import '../../network/Api.dart';
import '../../utils/provider.dart';

//我的额度
class WalletUi extends StatelessWidget {
  const WalletUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _WalletUiWidget();
  }
}

class _WalletUiWidget extends StatefulWidget {
  const _WalletUiWidget({Key? key}) : super(key: key);

  @override
  State<_WalletUiWidget> createState() => _WalletUiWidgetState();
}

class _WalletUiWidgetState extends State<_WalletUiWidget> {
  String str = "";
  final _listData = [];
  Map _data = {};
  int _page = 1;
  bool isLoading = false;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    str = "123";
    _getWalletList(_page);
    _gettotalIncome();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getMore();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      bgColor: const Color(0xFFF9F9F9),
      title: "我的额度",
      childWidget: str.isNotEmpty
          ? _buildContent()
          : SizedBox(
              height: 500,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Center(
                    child: Image.asset(
                      'images/no_data.png',
                      width: 175,
                      height: 122,
                    ),
                  ),
                ],
              ),
            ),
    );
  }

  /// 下拉刷新方法,为list重新赋值
  Future<void> _onRefresh() async {
    await Future.delayed(const Duration(seconds: 3), () {});
  }

  /// 上拉加载更多
  Future _getMore() async {
    if (!isLoading) {
      setState(() {
        isLoading = true;
      });
      await Future.delayed(const Duration(seconds: 1), () {});
    }
  }

  _getWalletList(int page) async {
    final res = await Api.getInstance().walletIncomeList(_page, 10);
    final data = res['data']['list'];

    if (data != null) {
      List list = data;
      if (list.isNotEmpty) {
        _listData.clear();
        setState(() {
          _listData.addAll(list);
        });
      }
    }
  }

  _gettotalIncome() async {
    final res = await Api.getInstance().totalIncome(Provider.memberId);
    final data = res['data'];

    if (res['code'] == 0 && res['data'] != null) {
      _data = data;
    }
  }

  /// 内容区域
  Widget _buildContent() {
    return NestedScrollView(
        headerSliverBuilder: (ctx, scrolled) {
          return [_buildHeadInfo()];
        },
        body: Column(
          children: [
            // _buildFilter(),
            Expanded(child: _buildListView())
          ],
        ));
  }

  /// 钱包信息
  Widget _buildHeadInfo() {
    return SliverToBoxAdapter(
      child: Container(
        height: 164,
        margin: const EdgeInsets.all(12),
        child: Stack(
          children: [
            Image.asset(
              'images/ic_wallet.png',
              width: MediaQuery.of(context).size.width - 24,
              fit: BoxFit.fill,
              color: ThemeColor.appColor,
            ),
            Container(
              margin: const EdgeInsets.only(left: 14, top: 20),
              child: Text.rich(
                TextSpan(children: [
                  const TextSpan(
                      text: "我的收入（元）",
                      style: TextStyle(fontSize: 14, color: Colors.white)),
                  TextSpan(
                      text: "\n" +
                          (_data['totalAmount'].toString() != 'null'
                              ? _data['totalAmount'].toString()
                              : '0'), //_data['totalAmount']
                      style: const TextStyle(
                          fontSize: 30,
                          color: Colors.white,
                          fontWeight: FontWeight.w600)),
                ]),
              ),
            ),
            // Align(
            //   alignment: Alignment.topRight,
            //   child: Container(
            //     height: 30,
            //     width: 52,
            //     margin: const EdgeInsets.only(top: 20, right: 14),
            //     alignment: Alignment.center,
            //     decoration: ShapeDecoration(
            //         shape: RoundedRectangleBorder(
            //             borderRadius: BorderRadius.circular(16)),
            //         color: Colors.white),
            //     child: GestureDetector(
            //       onTap: () {},
            //       child: Text(
            //         "提现",
            //         style: TextStyle(fontSize: 14, color: ThemeColor.textColor),
            //       ),
            //     ),
            //   ),
            // ),
            //  Container(
            //    margin: const EdgeInsets.only(left: 14,bottom: 20),
            //   alignment: Alignment.bottomLeft,
            //   child: Text.rich(TextSpan(
            //       children: [
            //         const TextSpan(text: "活动收入（元）",
            //             style: TextStyle(color: Colors.white, fontSize: 14)),
            //         TextSpan(text: "\n" + '0.00',//_data['totalAmount']
            //             style: TextStyle(color: Colors.white,
            //                 fontSize: 20,
            //                 fontWeight: FontWeight.w600)),
            //       ]
            //   )),
            // ),
            //  Container(
            //    margin: const EdgeInsets.only(right: 14,bottom: 20),
            //   alignment: Alignment.bottomRight,
            //   child: const Text.rich(TextSpan(
            //       children: [
            //         TextSpan(text: "邀请收入（元）",
            //             style: TextStyle(color: Colors.white, fontSize: 14)),
            //         TextSpan(text: "\n0.00",
            //             style: TextStyle(color: Colors.white,
            //                 fontSize: 20,
            //                 fontWeight: FontWeight.w600)),
            //       ]
            //   )),
            // )
          ],
        ),
      ),
    );
  }

  /// 筛选
  Widget _buildFilter() {
    return Container(
      height: 58,
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () {},
            child: Container(
              width: 96,
              height: 30,
              decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5)),
                  color: const Color(0xFFF3F4F7)),
              alignment: Alignment.center,
              child: IconText(
                "2022年05月",
                style: TextStyle(color: ThemeColor.textColor, fontSize: 12),
                textAlign: TextAlign.end,
                icon: Icon(
                  Icons.arrow_drop_down,
                  color: ThemeColor.textColor,
                  size: 12,
                ),
                beforeText: false,
              ),
            ),
          ),
          const SizedBox(
            width: 12,
          ),
          Row(
            children: const [
              Text.rich(TextSpan(children: [
                TextSpan(
                    text: "收 ",
                    style: TextStyle(
                      fontSize: 12,
                      color: Color(0xff69D97B),
                    )),
                TextSpan(
                    text: "0.00",
                    style: TextStyle(
                        color: Color(0xff909090),
                        fontSize: 12,
                        fontWeight: FontWeight.bold)),
              ])),
              Text.rich(TextSpan(children: [
                TextSpan(
                    text: "支 ",
                    style: TextStyle(
                      fontSize: 12,
                      color: Color(0xffD96969),
                    )),
                TextSpan(
                    text: "0.00",
                    style: TextStyle(
                        color: Color(0xff909090),
                        fontSize: 12,
                        fontWeight: FontWeight.bold)),
              ]))
            ],
          ),
        ],
      ),
    );
  }

  /// 列表
  Widget _buildListView() {
    print('-----------');
    print(_listData.length);

    return Stack(
      children: <Widget>[
        RefreshIndicator(
          onRefresh: _onRefresh,
          child: ListView.builder(
            itemCount: _listData.length,
            controller: _scrollController,
            itemBuilder: (ctx, index) {
              // return _buildItem(_listData?[index],index);
              if (index == _listData.length) {
                //加载更多
                return _getMoreWidget();
              } else {
                if (_listData?.isNotEmpty == true) {
                  return _buildItem(_listData?[index], index);
                } else {
                  return Container();
                }
              }
            },
          ),
        ),
      ],
    );
  }

  /// 月份汇总
  Widget _buildMonthSummary() {
    return Container(
      height: 58,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      alignment: Alignment.centerLeft,
      child: Text.rich(TextSpan(children: [
        TextSpan(
            text: "2020年5月",
            style: TextStyle(color: ThemeColor.textColor, fontSize: 13)),
        TextSpan(
            text: "\n活动收入:77432 元    邀请人收入:32 元",
            style: TextStyle(color: ThemeColor.textColorSecond, fontSize: 12))
      ])),
    );
  }

  /// 列表item
  Widget _buildItem(Map map, int index) {
    return Container(
      height: 58,
      margin: const EdgeInsets.symmetric(horizontal: 12),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              bottom: BorderSide(width: 1, color: ThemeColor.dividerColor))),
      child: Row(
        children: [
          Expanded(
            child: Text.rich(TextSpan(children: [
              TextSpan(
                text: map['remark'],
                style: TextStyle(color: Colors.black, fontSize: 14),
              ),
              TextSpan(
                  text: '\r\n' + map['bbrqWeek'] + map['bbrqAtime'],
                  // "\r\n星期二 下午1:14",
                  style: TextStyle(
                      color: ThemeColor.textColorSecond, fontSize: 11))
            ])),
          ),
          Text(
            map['type'] == 0
                ? '+' + map['amount'].toString()
                : '-' + map['amount'].toString(),
            style: TextStyle(
                color: Color(0xff69D97B),
                fontSize: 20,
                fontWeight: FontWeight.w600),
          )
        ],
      ),
    );
  }

  Widget _getMoreWidget() {
    return Center(
      child: Offstage(
        offstage: !isLoading,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: const <Widget>[
            Text(
              '加载中...',
              style: TextStyle(fontSize: 16.0),
            ),
            CircularProgressIndicator(
              strokeWidth: 1.0,
            )
          ],
        ),
      ),
    );
  }

  Widget gettype() {
    return SizedBox(
      height: 500,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Image.asset(
              'images/MeLook.png',
              width: 175,
              height: 122,
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context, 0);
              },
              child: Container(
                height: 38,
                width: 104,
                child: const Text('返回'),
                alignment: Alignment.center,
              ),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.white),
                foregroundColor: MaterialStateProperty.all(Color(0xFF7F69D9)),
                elevation: MaterialStateProperty.all(0),
                side: MaterialStateProperty.all(
                    const BorderSide(width: 1, color: Color(0xFF7F69D9))),
                //边框
                shape: MaterialStateProperty.all(const StadiumBorder(
                    side: BorderSide(
                  //设置 界面效果
                  style: BorderStyle.solid,
                  color: Color(0xFF7F69D9),
                ))), //圆
              ),
            ),
          ],
        ),
      ),
    );
  }
}
